/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.onduty.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import me.zhengjie.modules.onduty.domain.Onduty;
import me.zhengjie.modules.utils.DownExcelTemp;
import me.zhengjie.modules.utils.DownLoadUtil;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.onduty.repository.OndutyRepository;
import me.zhengjie.modules.onduty.service.OndutyService;
import me.zhengjie.modules.onduty.service.dto.OndutyDto;
import me.zhengjie.modules.onduty.service.dto.OndutyQueryCriteria;
import me.zhengjie.modules.onduty.service.mapstruct.OndutyMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2021-10-30
**/
@Service
@RequiredArgsConstructor
public class OndutyServiceImpl implements OndutyService {

    private final OndutyRepository ondutyRepository;
    private final OndutyMapper ondutyMapper;
    private static String warningInfo = "带*号的列请选择下拉框内的数据，红色字体为必填项";

    @Override
    public Map<String,Object> queryAll(OndutyQueryCriteria criteria, Pageable pageable){
        Page<Onduty> page = ondutyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(ondutyMapper::toDto));
    }

    @Override
    public List<OndutyDto> queryAll(OndutyQueryCriteria criteria){
        return ondutyMapper.toDto(ondutyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<Onduty> selectAll(String start,String end) {
        return ondutyRepository.findByTimeBetween(start, end);
    }

    @Override
    @Transactional
    public OndutyDto findById(String id) {
        Onduty onduty = ondutyRepository.findById(id).orElseGet(Onduty::new);
        ValidationUtil.isNull(onduty.getId(),"Onduty","id",id);
        return ondutyMapper.toDto(onduty);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OndutyDto create(Onduty resources) {
        resources.setId(IdUtil.simpleUUID()); 
        return ondutyMapper.toDto(ondutyRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Onduty resources) {

        Onduty onduty = ondutyRepository.findById(resources.getId()).orElseGet(Onduty::new);
        ValidationUtil.isNull( onduty.getId(),"Onduty","id",resources.getId());
        onduty.copy(resources);
        ondutyRepository.save(onduty);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            ondutyRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<OndutyDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (OndutyDto onduty : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("日期", onduty.getTime());
            map.put("名称", onduty.getName());
            map.put("内容", onduty.getContent());
            map.put("创建者", onduty.getCreateBy());
            map.put("更新者", onduty.getUpdateBy());
            map.put("创建日期", onduty.getCreateTime());
            map.put("更新时间", onduty.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> upload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            ExcelReader reader;
            reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias("日期", "time");
            reader.addHeaderAlias("名称", "name");
            reader.addHeaderAlias("内容", "content");
            List<Onduty> list = reader.readAll(Onduty.class);
            List<Onduty> result = new ArrayList<>();
            list.remove(0);
            for (Onduty onduty: list) {
                onduty.setId(IdUtil.simpleUUID());
                result.add(onduty);
            }
            ondutyRepository.saveAll(result);
            map.put("state", "success");
            map.put("info", "导入" + list.size() + "条数据，成功" + result.size() + "条");
        } catch (IOException e) {
            map.put("state", "error");
            map.put("message", "导入失败");
        }
        return map;
    }

    @Override
    public void exportTemplate(HttpServletResponse response) throws IOException {
        String newFilePath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
        //模板名称
        String fileName = "信息模板";
        //设置头
        String[] headers = {"日期", "名称", "内容"};
        Integer[] mandatory = {0, 1, 2, 4, 5, 10};
        List<String> headerList = new ArrayList<>();
        for (int i = 0; i < headers.length; i++) {
            headerList.add(headers[i]);
        }
        //存放数据集
        List<List<String>> downData = new ArrayList<>();
        //数据所在列
        List<String> downRows = Lists.newArrayList();
        downRows.add("0");
        downRows.add("2");
        downRows.add("3");
        //生成待下载excel模板
        DownExcelTemp.createExcelTemplate(newFilePath, fileName, headerList, downData, downRows, mandatory, warningInfo);
        //下载模板
        DownLoadUtil.downFile(newFilePath, fileName, response);
        //删除临时文件
        File delFile = new File(newFilePath);
        if (delFile.exists()) {
            delFile.delete();
        }
    }

    @Override
    public List<Onduty> getAllData() {
        return ondutyRepository.findAll();
    }
}